/*
 *  DBConnection.cpp
 *  SpaceTrader
 *
 *  Created by Jake on 12/7/12.
 *  Copyright 2012 The Hex Pistols. All rights reserved.
 *
 */

#include "DBConnection.h"
#include <iostream>
#include <mongo/client/dbclient.h>

bool DBLogin(std::string username, std::string password)
{
	mongo::DBClientConnection c;
	std::string errmsg;
	if(!c.connect("localhost",errmsg)) return false;
	
	std::auto_ptr<mongo::DBClientCursor> cursor = 
		c.query("test.users",QUERY("username" << username << "password" << password));
				
	return cursor->more();
}

bool DBCheckUser(std::string username)
{
	mongo::DBClientConnection c;
	std::string errmsg;
	if(!c.connect("localhost",errmsg)) return false;
	
	std::auto_ptr<mongo::DBClientCursor> cursor = 
	c.query("test.users",QUERY("username" << username));
	
	return cursor->more();
}

void DBAddUser(std::string username, std::string password)
{
	mongo::DBClientConnection c;
	std::string errmsg;
	if(!c.connect("localhost",errmsg)) return;
	
	mongo::BSONObj p = BSON("username" << username << "password" << password);
	c.insert("test.users", p);
}
	
void DBSaveFileInsert(std::string username, std::string data)
{
	mongo::DBClientConnection c;
	std::string errmsg;
	if(!c.connect("localhost",errmsg)) return;
	
	mongo::BSONObj p = BSON("username" << username << "data" << data);
	c.insert("test.savefile", p);
}

std::string DBSaveFileRetrieve(std::string username)
{
	mongo::DBClientConnection c;
	std::string errmsg;
	if(!c.connect("localhost",errmsg)) return NULL;
	
	std::auto_ptr<mongo::DBClientCursor> cursor = 
		c.query("test.savefile",QUERY("username" << username));
	
	return (cursor->more())?cursor->next().getField("data").String():"";
}